/**
 * desc: 公用的下拉搜索框
 * @ type: {string} shop: 供应商搜索  goods: 商品搜索 默认为供应商
 * @ storeId: {string} 供应商id  type为goods必须传入
 * @ placeholder: {string} 提示语句，默认为空
 * @ onChange: {func} 选择项发生变化时的事件
 * @ index: {number} 如果是在表格中，把下标返回
 *
 */

import React, { useState, useEffect } from 'react';
import { queryFactoryList, queryGoodsList } from '@/services/common';
import { find } from 'lodash';
import { Select } from 'antd';

const { Option } = Select;

let timeout;
let currentValue;

function fetch(value, type, storeId, callback) {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }

  currentValue = value;

  async function fake() {
    if (type == 'goods') {
      //如果是商品，走商品接口
      const res = await queryGoodsList({
        storeId,
        goodsName: value,
        size: 50,
        current: 1,
      });
      if (res.success) {
        const {
          data: { records },
        } = res;
        callback(records);
      } else {
        callback([]);
      }
    } else {
      //否则走供应商接口
      const res = await queryFactoryList({
        storeName: value,
        size: 50,
        current: 1,
      });
      if (res.success) {
        const {
          data: { records },
        } = res;
        callback(records);
      } else {
        callback([]);
      }
    }
  }
  timeout = setTimeout(fake, 300);
}

export default ({
  width = 160,
  type = 'shop',
  value = undefined,
  storeId = null,
  placeholder = '请输入供应商名称',
  onChange = null,
  index = null,
}) => {
  const [ data, setData ] = useState([]);

  const [ loading, setLoading ] = useState(false);

  //搜索事件触发
  const handleSearch = (value) => {
    if (value) {
      setLoading(true);
      fetch(value, type, storeId, (data) => {
        setLoading(false);
        setData(data);
      });
    } else {
      setData([]);
    }
  };

  const getInitialData = async () => {
    setLoading(true);
    if (type == 'goods') {
      const res = await queryGoodsList({
        storeId: storeId,
        goodsId: value,
        size: 50,
        current: 1,
      });
      if (res.success) {
        const {
          data: { records },
        } = res;
        setData(records);
      }
    } else {
      const res = await queryFactoryList({
        storeId: value,
        size: 50,
        current: 1,
      });
      if (res.success) {
        const {
          data: { records },
        } = res;
        setData(records);
      }
    }
    setLoading(false);
  };

  useEffect(() => {
    if (value) {
      getInitialData();
    }
  }, []);

  //点击选择事件
  const handleChange = (val) => {
    if (type == 'goods') {
      const obj = find(data, (v) => v.goodsId == val);
      onChange(obj, index);
    } else {
      const obj = find(data, (v) => v.storeId == val);
      onChange(val, index, obj);
    }
  };

  //商品下拉是否可选
  const isAble = () => {
    if (type == 'goods') {
      if (storeId != 0 && !storeId) {
        return true;
      } else {
        return false;
      }
    }
    return false;
  };
  const options =
    type == 'goods'
      ? data.map((d) => (
          <Option value={d.goodsId} key={d.goodsId}>
            {d.goodsName}
          </Option>
        ))
      : data.map((d) => (
          <Option value={d.storeId} key={d.storeId}>
            {d.storeName}
          </Option>
        ));
  return (
    <Select
      showSearch
     
      disabled={isAble()}
      style={{ width: width }}
      value={value}
      placeholder={placeholder}
      defaultActiveFirstOption={false}
      showArrow={false}
      filterOption={false}
      dropdownMatchSelectWidth={false}
      onSearch={handleSearch}
      onChange={handleChange}
      notFoundContent={loading ? '加载中...' : 'Not Data' }
    >
      {options}
    </Select>
  );
};
